package dubbo.server2.impl.controller;

import org.apache.cxf.common.util.CollectionUtils;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.File;
import java.util.Collections;
import java.util.List;

@Controller
@RequestMapping("/dom4j")
public class Dom4jController {
    @RequestMapping("/findElementXpath")
    @ResponseBody
    public String findElementXpath(String element) {
        Document document = load("D:\\user\\01384865\\Java\\ideaProjects\\DubboServer\\dubbo.server2.impl\\src\\main\\webapp\\WEB-INF\\file\\入库单.xml");
        String xpath = findElementXpath(document.getRootElement(), element);
        return xpath;
    }

    public static Document load(String filename) {
        Document document = null;
        try {
            SAXReader saxReader = new SAXReader();
            document = saxReader.read(new File(filename)); // 读取XML文件,获得document对象
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return document;
    }

    private String findElementXpath(Element element, String qName) {
        if (element.getQName().getName().equals(qName))
            return element.getUniquePath();
        else {
            List<Element> elements = element.elements();
            if (!CollectionUtils.isEmpty(elements)) {
                for (Element element1 : elements) {
                    String ret= findElementXpath(element1, qName);
                    if(ret!=null) return ret;
                }
            }
            return null;
        }

    }
}
